class Solution {
    int[] dx = {0,0,1,-1};
    int[] dy = {1,-1,0,0};
    int m = 0;
    int n = 0;
    boolean[][] check;
    public boolean exist(char[][] board, String word) {
        m = board.length;
        n = board[0].length;
        check = new boolean[m][n];
        char ch = word.charAt(0);
        // 找到起始字母的位置
        for(int i = 0; i < m; i++){
            for(int j = 0; j < n; j++){
                if(board[i][j] == ch){
                    if(dfs(board, i, j, word, 1) == true){
                        return true;
                    }
                }
            }
        }
        return false;
    }
    public boolean dfs(char[][] board, int i, int j, String word, int pos){
        // 递归的出口
        if(pos == word.length()){
            return true;
        }
        char ch = word.charAt(pos);
        check[i][j] = true;
        // 判断上下左右四个位置是否能匹配下一个字符
        for(int k = 0; k < 4; k++){
            int x = i + dx[k];
            int y = j + dy[k];
            // 坐标合法
            if(x >= 0 && x < m && y >= 0 && y < n && check[x][y] == false && board[x][y] == ch){
                if(dfs(board, x, y, word, pos + 1) == true){
                    return true;
                }
            }
        }
        check[i][j] = false;
        return false;
    }
}